package com.rtx.express.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.rtx.api.annotation.RtxExpressApi;
import com.rtx.common.Base64Helper;
import com.rtx.common.HttpUtils;
import com.rtx.common.JaxbObjectAndXmlUtil;
import com.rtx.common.MD5Helper;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.edi.model.express.sf.Body;
import com.rtx.edi.model.express.sf.Cargo;
import com.rtx.edi.model.express.sf.Order;
import com.rtx.edi.model.express.sf.SFRequest;
import com.rtx.edi.model.express.sf.SfResponse;
import com.rtx.edi.model.express.sf.SfRlsInfoDetail;
import com.rtx.express.service.IExpressService;

@RtxExpressApi(expressApiName = "丰桥-顺丰下单-顺丰标快")
@Service("快递接口SFBK")
public class SFBKExpressAPI  implements IExpressService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	private static String  create_order_url="http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService";
	
	private static String sfCheckword="FHsFlIb96ZCnPw4JWe5wGNflinbtTgug";
	private static String SfCustid="5125857619";
	/**
	 * 处理顺丰标快请求接口
	 * @return
	 */
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApiConfig config = bo.getExpressConfig();
		PlExpressApi task =  bo.getExpressTask();
		try {
			mappingConfig(config);
			//转化顺丰请求
			SFRequest request = coverToSFTHRequest(bo);
			//发顺丰快递数据xml内容
			String reqXml = JaxbObjectAndXmlUtil.object2Xml(request);
			//生成顺丰校验码
			String verifyCode = reqXml+sfCheckword;
			verifyCode = Base64Helper.encode(MD5Helper.encryptMD5(verifyCode, "UTF-8"));
 			Map<String,String> params=new HashMap<String, String>();
 			params.put("xml", reqXml);
 			params.put("verifyCode", verifyCode);
			
 			Map<String,String> map = new HashMap<String,String>();
			map.put("xml", reqXml);//
			map.put("verifyCode", verifyCode);
			log.info("订单-"+task.getExternorderkey()+"-获取顺丰标快快递单号请求数据：" + reqXml);
			//发送请求
			String resXml = HttpUtils.sendPostHttp(create_order_url, map);
			log.info("订单-"+task.getExternorderkey()+"-获取顺丰标快快递单号返回结果：" + resXml);
			SfResponse sfRes = JaxbObjectAndXmlUtil.xml2Object(resXml, SfResponse.class); 			
 			
			if("OK".equals(sfRes.getHead())) {
				bo.setCallCreateOrderAPIResult("ok");
				bo.setCallCreateOrderAPIData(resXml);
			}else {
				bo.setCallCreateOrderAPIData(resXml);
				bo.setMsg(sfRes.getError().getMsg());
			}
		} catch (Exception e) {
			log.info("订单-{}-获取顺丰标快快递单号失败：{}",task.getExternorderkey(),e);
		}
	}
	
	void mappingConfig(PlExpressApiConfig config){
		if(!StringUtils.hasLength(config.getSfCustid())) {
			config.setSfCustid(SfCustid);
		}
	}

	/**
	 * 转化成顺丰标快请求
	 * @return
	 * @throws JAXBException 
	 */
	public static SFRequest coverToSFTHRequest(ExpressBO bo) throws JAXBException {
		PlExpressApi task =  bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		SFRequest request = new SFRequest(); 
		
		Order order = new Order();
		if(bo.getZdflag() == true) {
			order.setOrderid(task.getExternorderkey()+System.currentTimeMillis());
		}else {
			order.setOrderid(task.getExternorderkey());
		}
		order.setIs_gen_bill_no("1");
		order.setJ_company(task.getSendCompanyName());
		order.setJ_contact(task.getSendName());
		order.setJ_tel(task.getSendPhone());
		order.setJ_province(task.getSendProvince());
		order.setJ_city(task.getSendCity());
		order.setJ_county(task.getSendCounty());
		order.setJ_address(task.getSendAddress());
		
		order.setD_company(task.getReceiverCompanyName());
		order.setD_contact(task.getReceiverName());
		order.setD_tel(task.getReceiverPhone());
		order.setD_mobile(task.getReceiverMobile());
		order.setD_province(task.getReceiverProvince());
		order.setD_city(task.getReceiverCity());
		order.setD_county(task.getReceiverCounty());
		order.setD_address(task.getReceiverAddress());
		order.setCustid(config.getSfCustid());
																			
		order.setPay_method("1");		
		order.setExpress_type("1");
		order.setRoutelabelForReturn("1");
		order.setRoutelabelService("1");
		order.setRemark("");
		
		Cargo cargo = new Cargo();
		cargo.setName("服装");
		cargo.setCount("1");
		
		
		request.setHead("cfwl");
		Body body = new Body();
		body.setOrder(order);
		order.setCargo(cargo);
		request.setBody(body);
		return request;
	}

	/*
	 * <?xml version='1.0' encoding='UTF-8'?>
		<Response service="OrderService">
		    <Head>OK</Head>
		    <Body>
		        <OrderResponse mailno="SF1163911981997" filter_result="2" orderid="test001" destcode="755WE-AG-UDL003A同" origincode="755">
		            <rls_info invoke_result="OK" rls_code="1000" rls_errormsg="SF1163911981997:">
		                <rls_detail waybillNo="SF1163911981997" sourceTransferCode="755WE" sourceCityCode="755" sourceDeptCode="755AG" destCityCode="755" destDeptCode="755AG" destTeamCode="755UDL003" destTransferCode="755WE" destRouteLabel="755WE-AG-UDL003A同" proName="顺丰标快" cargoTypeCode="T6" limitTypeCode="T6" expressTypeCode="B1" codingMapping="K4" xbFlag="0" printFlag="000000000" twoDimensionCode="MMM={'k1':'755WE','k2':'755AG','k3':'755UDL003','k4':'T801','k5':'SF1163911981997','k6':'','k7':'34201639'}" proCode="T801" printIcon="00000000" checkCode="34201639" destGisDeptCode="755AG"/>
		            </rls_info>
		        </OrderResponse>
		    </Body>
		</Response>
	 */
	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
		try {
			if("ok".equals(bo.getCallCreateOrderAPIResult())) {
				PlExpressResult result = bo.getExpressResultFillSendAndReceiver();
				result.setResponseStr(bo.getCallCreateOrderAPIData());
				result.setExternorderkey(task.getExternorderkey());
				
				SfResponse sfRes = JaxbObjectAndXmlUtil.xml2Object(bo.getCallCreateOrderAPIData(), SfResponse.class);
				SfRlsInfoDetail de  = sfRes.getBody().getOrder().getSfRlsInfo().getSfRlsInfoDetail();
				
				result.setSfcargoTypeCode(de.getCargoTypeCode());
				result.setSfcheckCode(de.getCheckCode());
				result.setSfcodingMapping(de.getCodingMapping());
				result.setSfdestCityCode(de.getDestCityCode());
				result.setSfdestcode(sfRes.getBody().getOrder().getDestcode());
				result.setSfdestDeptCode(de.getDestDeptCode());
				result.setSfdestGisDeptCode(de.getDestGisDeptCode());
				result.setSfdestRouteLabel(de.getDestRouteLabel());
				result.setSfdestTeamCode(de.getDestTeamCode());
				result.setSfdestTransferCode(de.getDestTransferCode());
				result.setSfexpressTypeCode(de.getExpressTypeCode());
				result.setSflimitTypeCode(de.getLimitTypeCode());
				result.setSforigincode(sfRes.getBody().getOrder().getOrigincode());
				result.setSfprintFlag(de.getPrintFlag());
				result.setSfprintIcon(de.getPrintIcon());
				result.setSfproName(de.getProName());
				result.setSfsourceCityCode(de.getSourceCityCode());
				result.setSfsourceDeptCode(de.getSourceDeptCode());
				result.setSfsourceTransferCode(de.getSourceTransferCode());
				result.setSftwoDimensionCode(de.getTwoDimensionCode());
				result.setSfxbFlag(de.getXbFlag());
				bo.setExpressResult(result);
				
				result.setWaybillNo(sfRes.getBody().getOrder().getMailno());
			}
		} catch (Exception e) {
			log.info("订单-{}-获取顺丰标快快递单号 解析响应结果-{}-异常-{}",task.getExternorderkey(),bo.getCallCreateOrderAPIData(),e);
			bo.setMsg(bo.getMsg());
		}
		
	}  
}
